package org.wj.problem;

import java.util.*;

public class Convert {

	public static void main(String[] args) {
		String leetcode = convert("", 4);
		System.out.println(leetcode);
	}


	public static String convert(String s, int numRows) {
		int cycle = 2 * numRows - 2;
		char[] chars = s.toCharArray();
		Map<Integer, List<Character>> lineRelation = new HashMap<>();
		int line = 0;
		int direction = 1;
		for (int i = 0; i < chars.length; i++) {
			List<Character> characters;
			int reminder;
			if (cycle > 0) {
				reminder = (i + 1) % cycle;
			} else {
				reminder = 1;
			}
			if (reminder == 0) {
				characters = lineRelation.get(2);
				if (characters == null) {
					characters = new ArrayList<>();
					characters.add(chars[i]);
					lineRelation.put(2, characters);
				} else {
					characters.add(chars[i]);
				}
				line = 0;
				direction = 1;
			} else if (reminder > numRows) {
				direction = -1;
				line += direction;
				characters = lineRelation.get(line);
				if (characters == null) {
					characters = new ArrayList<>();
					characters.add(chars[i]);
					lineRelation.put(line, characters);

				} else {
					characters.add(chars[i]);
				}
			} else {
				line += direction;
				characters = lineRelation.get(line);
				if (characters == null) {
					characters = new ArrayList<>();
					characters.add(chars[i]);
					lineRelation.put(line, characters);

				} else {
					characters.add(chars[i]);
				}

			}
		}
		StringBuilder result = new StringBuilder(s.length());
		for (int i = 1; i <= lineRelation.size(); i++) {
			List<Character> list = lineRelation.get(i);
			for (Character character : list) {
				result.append(character);
			}
		}
		return result.toString();
	}
}
